import React, { useState, useEffect } from 'react';
import {
  Table, Button, Space, Dropdown, Modal, Input, message, Tag, Tooltip,
  Typography, Avatar, Progress, Popconfirm, Select, DatePicker, Card,
  Row, Col, Statistic, Empty, Spin
} from 'antd';
import {
  FileOutlined, FolderOutlined, DownloadOutlined, ShareAltOutlined,
  EditOutlined, DeleteOutlined, CopyOutlined, ScissorOutlined,
  EyeOutlined, MoreOutlined, SearchOutlined, FilterOutlined,
  SortAscendingOutlined, ReloadOutlined, PlusOutlined
} from '@ant-design/icons';
import type { ColumnsType, TableProps } from 'antd/es/table';
import { fileService, FileItem, FileSearchParams } from '@/services/fileService';
import FileUpload from './FileUpload';

const { Text, Title } = Typography;
const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;

interface FileListProps {
  folderId?: string;
  onFileSelect?: (file: FileItem) => void;
  onFolderChange?: (folderId: string) => void;
  selectable?: boolean;
  showUpload?: boolean;
  className?: string;
  style?: React.CSSProperties;
}

interface FileListState {
  files: FileItem[];
  loading: boolean;
  selectedRowKeys: string[];
  selectedFiles: FileItem[];
  pagination: {
    current: number;
    pageSize: number;
    total: number;
  };
  searchParams: FileSearchParams;
  sortBy: string;
  sortOrder: 'asc' | 'desc';
}

export default function FileList({
  folderId,
  onFileSelect,
  onFolderChange,
  selectable = true,
  showUpload = true,
  className,
  style
}: FileListProps) {
  const [state, setState] = useState<FileListState>({
    files: [],
    loading: false,
    selectedRowKeys: [],
    selectedFiles: [],
    pagination: {
      current: 1,
      pageSize: 20,
      total: 0
    },
    searchParams: {},
    sortBy: 'name',
    sortOrder: 'asc'
  });

  const [showUploadModal, setShowUploadModal] = useState(false);
  const [showCreateFolderModal, setShowCreateFolderModal] = useState(false);
  const [newFolderName, setNewFolderName] = useState('');
  const [showSearchPanel, setShowSearchPanel] = useState(false);
  const [renameModalVisible, setRenameModalVisible] = useState(false);
  const [renamingFile, setRenamingFile] = useState<FileItem | null>(null);
  const [newFileName, setNewFileName] = useState('');

  // 加载文件列表
  const loadFiles = async (params?: Partial<FileSearchParams>) => {
    setState(prev => ({ ...prev, loading: true }));
    
    try {
      const searchParams = { ...state.searchParams, ...params };
      const response = await fileService.getFiles(folderId, {
        page: state.pagination.current - 1,
        size: state.pagination.pageSize,
        sortBy: state.sortBy,
        sortOrder: state.sortOrder,
        ...searchParams
      });

      setState(prev => ({
        ...prev,
        files: response.content,
        pagination: {
          ...prev.pagination,
          total: response.totalElements
        },
        loading: false
      }));
    } catch (error: any) {
      console.error('加载文件列表失败:', error);
      message.error('加载文件列表失败');
      setState(prev => ({ ...prev, loading: false }));
    }
  };

  // 初始加载
  useEffect(() => {
    loadFiles();
  }, [folderId, state.pagination.current, state.pagination.pageSize, state.sortBy, state.sortOrder]);

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 获取文件图标
  const getFileIcon = (file: FileItem) => {
    if (file.type === 'folder') {
      return <FolderOutlined style={{ color: '#1890ff', fontSize: 16 }} />;
    }
    
    const iconStyle = { fontSize: 16 };
    const ext = file.extension?.toLowerCase();
    
    switch (ext) {
      case 'pdf':
        return <FileOutlined style={{ ...iconStyle, color: '#ff4d4f' }} />;
      case 'doc':
      case 'docx':
        return <FileOutlined style={{ ...iconStyle, color: '#1890ff' }} />;
      case 'xls':
      case 'xlsx':
        return <FileOutlined style={{ ...iconStyle, color: '#52c41a' }} />;
      case 'ppt':
      case 'pptx':
        return <FileOutlined style={{ ...iconStyle, color: '#fa8c16' }} />;
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
      case 'bmp':
        return <FileOutlined style={{ ...iconStyle, color: '#722ed1' }} />;
      case 'mp4':
      case 'avi':
      case 'mov':
        return <FileOutlined style={{ ...iconStyle, color: '#eb2f96' }} />;
      case 'mp3':
      case 'wav':
      case 'flac':
        return <FileOutlined style={{ ...iconStyle, color: '#13c2c2' }} />;
      default:
        return <FileOutlined style={iconStyle} />;
    }
  };

  // 处理文件点击
  const handleFileClick = (file: FileItem) => {
    if (file.type === 'folder') {
      if (onFolderChange) {
        onFolderChange(file.id);
      }
    } else {
      if (onFileSelect) {
        onFileSelect(file);
      }
    }
  };

  // 处理文件操作
  const handleFileAction = async (action: string, file: FileItem) => {
    try {
      switch (action) {
        case 'download':
          await fileService.downloadFile(file.id);
          message.success('下载开始');
          break;
        case 'preview':
          const previewUrl = await fileService.getPreviewUrl(file.id);
          window.open(previewUrl, '_blank');
          break;
        case 'rename':
          setRenamingFile(file);
          setNewFileName(file.name);
          setRenameModalVisible(true);
          break;
        case 'copy':
          // 实现复制逻辑
          message.info('复制功能开发中...');
          break;
        case 'move':
          // 实现移动逻辑
          message.info('移动功能开发中...');
          break;
        case 'share':
          // 实现分享逻辑
          message.info('分享功能开发中...');
          break;
        case 'delete':
          await fileService.deleteFile(file.id);
          message.success('删除成功');
          loadFiles();
          break;
        default:
          break;
      }
    } catch (error: any) {
      console.error(`${action}操作失败:`, error);
      message.error(`${action}操作失败`);
    }
  };

  // 批量操作
  const handleBatchAction = async (action: string) => {
    if (state.selectedRowKeys.length === 0) {
      message.warning('请先选择文件');
      return;
    }

    try {
      switch (action) {
        case 'delete':
          await fileService.deleteFiles(state.selectedRowKeys);
          message.success('批量删除成功');
          setState(prev => ({ ...prev, selectedRowKeys: [], selectedFiles: [] }));
          loadFiles();
          break;
        case 'download':
          // 实现批量下载
          message.info('批量下载功能开发中...');
          break;
        default:
          break;
      }
    } catch (error: any) {
      console.error(`批量${action}失败:`, error);
      message.error(`批量${action}失败`);
    }
  };

  // 创建文件夹
  const handleCreateFolder = async () => {
    if (!newFolderName.trim()) {
      message.error('请输入文件夹名称');
      return;
    }

    try {
      await fileService.createFolder(newFolderName, folderId);
      message.success('创建文件夹成功');
      setShowCreateFolderModal(false);
      setNewFolderName('');
      loadFiles();
    } catch (error: any) {
      console.error('创建文件夹失败:', error);
      message.error('创建文件夹失败');
    }
  };

  // 重命名文件
  const handleRename = async () => {
    if (!renamingFile || !newFileName.trim()) {
      message.error('请输入新名称');
      return;
    }

    try {
      await fileService.renameFile(renamingFile.id, newFileName);
      message.success('重命名成功');
      setRenameModalVisible(false);
      setRenamingFile(null);
      setNewFileName('');
      loadFiles();
    } catch (error: any) {
      console.error('重命名失败:', error);
      message.error('重命名失败');
    }
  };

  // 搜索文件
  const handleSearch = (params: FileSearchParams) => {
    setState(prev => ({
      ...prev,
      searchParams: params,
      pagination: { ...prev.pagination, current: 1 }
    }));
    loadFiles(params);
  };

  // 表格列定义
  const columns: ColumnsType<FileItem> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      sorter: true,
      render: (text: string, record: FileItem) => (
        <Space>
          {getFileIcon(record)}
          <Button 
            type="link" 
            onClick={() => handleFileClick(record)}
            style={{ padding: 0, height: 'auto' }}
          >
            {text}
          </Button>
          {record.isShared && <Tag color="blue">已分享</Tag>}
        </Space>
      )
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
      sorter: true,
      width: 100,
      render: (size: number, record: FileItem) => 
        record.type === 'folder' ? '-' : formatFileSize(size)
    },
    {
      title: '类型',
      dataIndex: 'mimeType',
      key: 'type',
      width: 120,
      render: (mimeType: string, record: FileItem) => {
        if (record.type === 'folder') return '文件夹';
        return record.extension?.toUpperCase() || '未知';
      }
    },
    {
      title: '修改时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      sorter: true,
      width: 180,
      render: (date: string) => new Date(date).toLocaleString()
    },
    {
      title: '创建者',
      dataIndex: 'createdByName',
      key: 'createdBy',
      width: 120,
      render: (name: string) => (
        <Space>
          <Avatar size="small">{name?.charAt(0)}</Avatar>
          <Text>{name}</Text>
        </Space>
      )
    },
    {
      title: '操作',
      key: 'actions',
      width: 120,
      render: (_, record: FileItem) => {
        const menuItems = [
          {
            key: 'preview',
            label: '预览',
            icon: <EyeOutlined />,
            disabled: record.type === 'folder'
          },
          {
            key: 'download',
            label: '下载',
            icon: <DownloadOutlined />,
            disabled: record.type === 'folder'
          },
          {
            key: 'share',
            label: '分享',
            icon: <ShareAltOutlined />
          },
          { type: 'divider' as const },
          {
            key: 'rename',
            label: '重命名',
            icon: <EditOutlined />
          },
          {
            key: 'copy',
            label: '复制',
            icon: <CopyOutlined />
          },
          {
            key: 'move',
            label: '移动',
            icon: <ScissorOutlined />
          },
          { type: 'divider' as const },
          {
            key: 'delete',
            label: '删除',
            icon: <DeleteOutlined />,
            danger: true
          }
        ];

        return (
          <Dropdown
            menu={{
              items: menuItems,
              onClick: ({ key }) => {
                if (key === 'delete') {
                  Modal.confirm({
                    title: '确认删除',
                    content: `确定要删除 "${record.name}" 吗？`,
                    onOk: () => handleFileAction(key, record)
                  });
                } else {
                  handleFileAction(key, record);
                }
              }
            }}
            trigger={['click']}
          >
            <Button type="text" icon={<MoreOutlined />} />
          </Dropdown>
        );
      }
    }
  ];

  // 表格配置
  const tableProps: TableProps<FileItem> = {
    columns,
    dataSource: state.files,
    loading: state.loading,
    rowKey: 'id',
    pagination: {
      current: state.pagination.current,
      pageSize: state.pagination.pageSize,
      total: state.pagination.total,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
      onChange: (page, pageSize) => {
        setState(prev => ({
          ...prev,
          pagination: { ...prev.pagination, current: page, pageSize: pageSize || 20 }
        }));
      }
    },
    rowSelection: selectable ? {
      selectedRowKeys: state.selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        setState(prev => ({
          ...prev,
          selectedRowKeys: selectedRowKeys as string[],
          selectedFiles: selectedRows
        }));
      }
    } : undefined,
    onChange: (pagination, filters, sorter) => {
      if (sorter && !Array.isArray(sorter)) {
        setState(prev => ({
          ...prev,
          sortBy: sorter.field as string,
          sortOrder: sorter.order === 'ascend' ? 'asc' : 'desc'
        }));
      }
    }
  };

  return (
    <div className={className} style={style}>
      {/* 工具栏 */}
      <Card size="small" style={{ marginBottom: 16 }}>
        <Row justify="space-between" align="middle">
          <Col>
            <Space>
              {showUpload && (
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />}
                  onClick={() => setShowUploadModal(true)}
                >
                  上传文件
                </Button>
              )}
              <Button 
                icon={<FolderOutlined />}
                onClick={() => setShowCreateFolderModal(true)}
              >
                新建文件夹
              </Button>
              <Button 
                icon={<ReloadOutlined />}
                onClick={() => loadFiles()}
              >
                刷新
              </Button>
            </Space>
          </Col>
          <Col>
            <Space>
              <Search
                placeholder="搜索文件..."
                allowClear
                onSearch={(value) => handleSearch({ keyword: value })}
                style={{ width: 200 }}
              />
              <Button 
                icon={<FilterOutlined />}
                onClick={() => setShowSearchPanel(!showSearchPanel)}
              >
                高级搜索
              </Button>
            </Space>
          </Col>
        </Row>

        {/* 批量操作 */}
        {state.selectedRowKeys.length > 0 && (
          <Row style={{ marginTop: 8 }}>
            <Col>
              <Space>
                <Text>已选择 {state.selectedRowKeys.length} 项</Text>
                <Button size="small" onClick={() => handleBatchAction('download')}>
                  批量下载
                </Button>
                <Popconfirm
                  title="确定要删除选中的文件吗？"
                  onConfirm={() => handleBatchAction('delete')}
                >
                  <Button size="small" danger>
                    批量删除
                  </Button>
                </Popconfirm>
              </Space>
            </Col>
          </Row>
        )}
      </Card>

      {/* 高级搜索面板 */}
      {showSearchPanel && (
        <Card size="small" style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={6}>
              <Select
                placeholder="文件类型"
                allowClear
                style={{ width: '100%' }}
                onChange={(value) => handleSearch({ type: value })}
              >
                <Option value="file">文件</Option>
                <Option value="folder">文件夹</Option>
              </Select>
            </Col>
            <Col span={6}>
              <Select
                placeholder="文件格式"
                allowClear
                style={{ width: '100%' }}
                onChange={(value) => handleSearch({ extension: value })}
              >
                <Option value="pdf">PDF</Option>
                <Option value="doc">Word</Option>
                <Option value="xls">Excel</Option>
                <Option value="jpg">图片</Option>
              </Select>
            </Col>
            <Col span={6}>
              <RangePicker
                placeholder={['开始日期', '结束日期']}
                style={{ width: '100%' }}
                onChange={(dates) => {
                  if (dates) {
                    handleSearch({
                      dateRange: {
                        start: dates[0]?.toISOString() || '',
                        end: dates[1]?.toISOString() || ''
                      }
                    });
                  }
                }}
              />
            </Col>
            <Col span={6}>
              <Button 
                block 
                onClick={() => {
                  setState(prev => ({ ...prev, searchParams: {} }));
                  loadFiles({});
                }}
              >
                清除筛选
              </Button>
            </Col>
          </Row>
        </Card>
      )}

      {/* 文件列表 */}
      <Card>
        {state.files.length === 0 && !state.loading ? (
          <Empty description="暂无文件" />
        ) : (
          <Table {...tableProps} />
        )}
      </Card>

      {/* 上传文件模态框 */}
      <Modal
        title="上传文件"
        open={showUploadModal}
        onCancel={() => setShowUploadModal(false)}
        footer={null}
        width={600}
      >
        <FileUpload
          folderId={folderId}
          onUploadSuccess={() => {
            setShowUploadModal(false);
            loadFiles();
          }}
        />
      </Modal>

      {/* 创建文件夹模态框 */}
      <Modal
        title="新建文件夹"
        open={showCreateFolderModal}
        onOk={handleCreateFolder}
        onCancel={() => {
          setShowCreateFolderModal(false);
          setNewFolderName('');
        }}
      >
        <Input
          placeholder="请输入文件夹名称"
          value={newFolderName}
          onChange={(e) => setNewFolderName(e.target.value)}
          onPressEnter={handleCreateFolder}
        />
      </Modal>

      {/* 重命名模态框 */}
      <Modal
        title="重命名"
        open={renameModalVisible}
        onOk={handleRename}
        onCancel={() => {
          setRenameModalVisible(false);
          setRenamingFile(null);
          setNewFileName('');
        }}
      >
        <Input
          placeholder="请输入新名称"
          value={newFileName}
          onChange={(e) => setNewFileName(e.target.value)}
          onPressEnter={handleRename}
        />
      </Modal>
    </div>
  );
}

// 导出类型
export type { FileListProps };